package com.h3bpm.web.service.impl;

import OThinker.Common.Data.Database.Parameter;
import OThinker.Common.Data.DbType;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Instance.InstanceContext;
import com.h3bpm.web.service.OutsourceService;
import com.h3bpm.web.utils.QjcUtils;
import data.DataException;
import data.DataRow;
import data.DataRowCollection;
import data.DataTable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static OThinker.H3.Controller.ControllerBase.getEngine;

@Service
public class OutsourceServiceImpl implements OutsourceService {
    private static final Logger logger = LoggerFactory.getLogger(OutsourceServiceImpl.class);

    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

    @Override
    public boolean updateExecutableTrue(String objectId) {
        String updateSql = "UPDATE i_outsourceProcedure SET executable = ? WHERE ObjectID = ?";
        Parameter[] params = new Parameter[2];
        params[0] = new Parameter("executable", DbType.String, "是");
        params[1] = new Parameter("ObjectID", DbType.String, objectId);
        int i = getEngine().getPortalQuery().ExcuteNoQuery(updateSql, params);
        logger.info("修改为可出门状态 参数 executable ：{} , ObjectID :  {}, 执行修改数量 ：{}","是",objectId,i);
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean updateExecutableFalse(String objectId) {
        String updateSql = "UPDATE i_outsourceProcedure SET executable = ? WHERE ObjectID = ?";
        Parameter[] params = new Parameter[2];
        params[0] = new Parameter("executable", DbType.String, "否");
        params[1] = new Parameter("ObjectID", DbType.String, objectId);
        int i = getEngine().getPortalQuery().ExcuteNoQuery(updateSql, params);
        logger.info("修改为不可出门状态 参数 executable ：{} , ObjectID :  {}, 执行修改数量 ：{}","否",objectId,i);
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Object processOutValid(String objectId) throws Exception {
        String pass = "通过";
        String notPass = "不通过";

        String count1  = String.format("select count(1)  from i_processout where ObjectID = '%s' and validProcessOutFlag ='%s';", objectId,pass);

        int count = getEngine().getPortalQuery().count(count1);

        if (count >0) {
            return pass;
        }

        String sqlsub = String.format("SELECT applicationFormId,processOutNum from i_applyprocessout WHERE ParentObjectID = '%s';", objectId);

        DataTable dataTable = getEngine().getPortalQuery().QueryTable(sqlsub);
        DataRowCollection rows = dataTable.getRows();


        Map<String,Integer> processData = getProcessData(rows);

        if (processData == null || processData.size() ==0){
            processDataSave(objectId,"validProcessOutFlag",notPass);
            return  notPass;
        }
        // 开始校验 出门数+已出门数<=批准数
        String  ids = StringUtils.join( processData.keySet(),"','");
        String sql = String.format("select objectId,processedOutNum,approvedNum from i_applyOutsource WHERE ObjectID in ('%s');", ids);

        logger.debug("获取sql:{}",sql);

        dataTable = getEngine().getPortalQuery().QueryTable(sql);

        rows = dataTable.getRows();

        DataRow dataRow;
        String rowsId;
        for (int i = 0; i < rows.size(); i++) {
            dataRow = rows.get(i);
            rowsId = dataRow.getString("objectId");
            int processedOutNum = dataRow.getInt("processedOutNum");
            int approvedNum = dataRow.getInt("approvedNum");

            // 出门数+已出们数 > 批准数 校验不通过
            if (QjcUtils.getInt(processData.get(rowsId)) + processedOutNum >approvedNum){
                processDataSave(objectId,"validProcessOutFlag",notPass);
                return  notPass;
            }
        }

        String sql1 = "update i_applyOutsource set processedOutNum = (processedOutNum +%s) where objectId = '%s'";
        // 修改 出门数
        for (Map.Entry<String,Integer> entry: processData.entrySet() ) {
            getEngine().getPortalQuery().ExcuteNoQuery(String.format(sql1, entry.getValue(),entry.getKey()));
        }


        processDataSave(objectId,"validProcessOutFlag",pass);

        return pass;
    }


    /**
     *  通过线程 线程设置出门 验证值
     *  业务动作调用服务时间超过10秒,流程节点会出现异常,
     *  h3方法获取流程数据 花费时间4到6秒,很容易超过10秒
     *
     * @param bizDataId
     * @param key
     * @param value
     */
    public void processDataSave(String bizDataId, String key, String value) {

        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {

                    String sql = String.format("SELECT ObjectID as id from ot_instancecontext WHERE BizObjectId = '%s';", bizDataId);
                    DataTable dataTable = getEngine().getPortalQuery().QueryTable(sql);
                    String instId = dataTable.getRows().get(0).getString("id");

                    InstanceContext instanceContext = getEngine().getInstanceManager().GetInstanceContext(instId);
                    long l =  System.currentTimeMillis();
                    InstanceData instanceData = new InstanceData(getEngine(), instId, User.AdministratorID);

                    instanceData.getBizObject().SetValue(key,value);

                    instanceData.Submit();

                    logger.info("线程设置出门 验证值 ,耗费时间:{}",System.currentTimeMillis()-l);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("线程设置出门 验证值 失败");
                }

            }
        });



    }


    @Override
    public Object updateProcessIn(String objectId) {
        logger.info("执行更新主表信息--开始");
        String pass = "通过";
        String notPass = "不通过";
        try {
            //查询是否已经通过
            String count1  = String.format("select count(1)  from i_processin where ObjectID = '%s' and validFlag ='%s';", objectId,pass);

            int count = getEngine().getPortalQuery().count(count1);

            if (count >0) {
                logger.info("count大于0，成功");
                return pass;
            }
            //a2.processOutNum>a2.processedInNum

            String sqlSub = String.format("SELECT applicationFormId,processOutObjId,returningNum, qualifyingNum,failingNum FROM i_applyprocessin WHERE ParentObjectID = '%s';", objectId);
            logger.debug("获取sql:{}",sqlSub);
            DataTable dataTable = getEngine().getPortalQuery().QueryTable(sqlSub);
            DataRowCollection tailRows = dataTable.getRows();

            Map<String,Integer> processInData = getProcessInData(tailRows);

            if (processInData == null || processInData.size() ==0){
                processDataSave(objectId,"validFlag",notPass);
                logger.info("无数据验证，失败");
                return  notPass;
            }
            // 开始校验
            String  ids = StringUtils.join( processInData.keySet(),"','");
            String sqlsub = String.format("SELECT objectId,processOutNum,processedInNum from i_applyProcessOut WHERE ObjectID in ('%s');", ids);
            logger.debug("获取sql:{}",sqlsub);
            dataTable = getEngine().getPortalQuery().QueryTable(sqlsub);
            DataRowCollection frontRows= dataTable.getRows();
            String rowsId;
            Integer processOutNum;
            Integer processedInNum;
            for (int i = 0; i < frontRows.size(); i++) {
                DataRow dataRow = frontRows.get(i);
                rowsId = dataRow.getString("objectId");
                processOutNum = frontRows.get(i).getInt("processOutNum");
                processedInNum = frontRows.get(i).getInt("processedInNum");
                // 已返厂数据+本次返厂数>出门数 校验不通过
                if (processOutNum-(QjcUtils.getInt(processInData.get(rowsId)) +processedInNum) <0 ){
                    processDataSave(objectId,"validFlag",notPass);
                    logger.info("已返厂数据+本次返厂数>出门数，失败");
                    return  notPass;
                }

            }

            String sql1 = "update i_applyOutsource set processedInNum = (processedInNum +%s),qualifiedNum = (qualifiedNum +%s),failNum = (failNum +%s),settlementNum=(settlementNum+%s) where objectId = '%s'";
            String sql2 = "update i_applyProcessOut set processedInNum = (processedInNum +%s) where objectId = '%s'";
            // 修改 出门数
            String processOutObjId;
            String applicationFormId;
            Integer returningNum;
            Integer qualifyingNum;
            Integer failingNum;

            for (int i = 0; i < tailRows.size(); i++) {
                //获取外包项目编码,产品编码,批准数量,已出门数,出门数
                processOutObjId = tailRows.get(i).getString("processOutObjId");
                applicationFormId = tailRows.get(i).getString("applicationFormId");
                returningNum = tailRows.get(i).getInt("returningNum");
                qualifyingNum = tailRows.get(i).getInt("qualifyingNum");
                failingNum = tailRows.get(i).getInt("failingNum");
                String wholeSql = String.format(sql1, returningNum, qualifyingNum, failingNum,qualifyingNum, applicationFormId);
                String wholeSql1 = String.format(sql2, returningNum, processOutObjId);
                getEngine().getPortalQuery().ExcuteNoQuery(wholeSql);
                getEngine().getPortalQuery().ExcuteNoQuery(wholeSql1);
            }
            processDataSave(objectId,"validFlag",pass);
            logger.info("数据正确修改成功");
            logger.info("执行更新主表信息--结束");
            return pass;
        } catch (Exception e) {
            e.printStackTrace();
            return notPass;
        }


    }

    /**
     * 月度结算
     * @param objectId
     * @return
     */
    @Override
    public Object settleDataWriteBack(String objectId) {
        String pass = "通过";
        String notPass = "不通过";
        try {

            //查询是否已经通过
            String count1  = String.format("select count(1)  from i_monthlySettlement where ObjectID = '%s' and validProcessOutFlag ='%s';", objectId,pass);

            int count = getEngine().getPortalQuery().count(count1);

            if (count >0) {
                return pass;
            }
            // 获取结算数据
            String sql  = String.format("select applyProcessInId,settleNum from i_settlementSub where ParentObjectID = '%s'", objectId);
            DataTable dataTable = getEngine().getPortalQuery().QueryTable(sql);

            Map<String, Integer> settleData = getSettleData(dataTable);

            if (settleData.isEmpty()) {
                notPass = "未获取到结算数据";
                processDataSave(objectId,"validProcessOutFlag",notPass);
                return  notPass;
            }

            //获取入门数据并校验  已结算+结算 不能大于待结算

            sql = String.format("select objectId,settlementNum,settledNum,qualifyingNum,applicationFormId,unitPrice from i_applyProcessIn WHERE ObjectID in ('%s');",
                    StringUtils.join(settleData.keySet(),"','"));
            logger.info("查询到的数据sql:{}", sql);
            dataTable = getEngine().getPortalQuery().QueryTable(sql);
            String applyProcessInId,applicationFormId = "";
            int settledNum,settlementNum,settleNum,qualifyingNum;

            Map<String, Integer> inSettleData = new HashMap<>();
            logger.info("查询到的数据有{}个", dataTable.getRows().size());
            BigDecimal  settleMoney = BigDecimal.valueOf(0);
            for (int i = 0; i < dataTable.getRows().size(); i++) {
                // 子表id
                applyProcessInId =  dataTable.getRows().get(i).getString("objectId");
                //已结算
                settledNum =  dataTable.getRows().get(i).getInt("settledNum");
                //待结算
                settlementNum =  dataTable.getRows().get(i).getInt("settlementNum");
                qualifyingNum =  dataTable.getRows().get(i).getInt("qualifyingNum");
                //本次结算
                settleNum = QjcUtils.getInt(settleData.get(applyProcessInId));

                String unitPrice =  dataTable.getRows().get(i).getString("unitPrice");

                BigDecimal price=new BigDecimal(unitPrice);
                BigDecimal num=new BigDecimal(settleNum);
                BigDecimal multiply = price.multiply(num);
                settleMoney = settleMoney.add(multiply);
                logger.info("第{}行，结算价格：{} 结算数：{} ，本行结算金额：{} ,累计结算金额：{}",i,unitPrice,settleNum,multiply,settleMoney);

                if (qualifyingNum < (settleNum+settledNum)){
                    notPass = "校验失败,结算数+已结算数>待结算数";
                    logger.info("校验失败,结算数+已结算数>待结算数：  结算数,{} 已结算数,{} 待结算数,{}, 合格品数,{},结算表的applyProcessInId即入库表的objectId:{}",settleNum,settledNum,settlementNum,qualifyingNum,applyProcessInId);
                    processDataSave(objectId,"validProcessOutFlag",notPass);
                    return  notPass;
                }
                applicationFormId =  dataTable.getRows().get(i).getString("applicationFormId");
                logger.info("主表信息id：{},结算数量：{}", applicationFormId, QjcUtils.getInt(inSettleData.get(applicationFormId)) +settleNum);
                inSettleData.put(applicationFormId,QjcUtils.getInt(inSettleData.get(applicationFormId))+settleNum);

            }

            //数据回写到 入门子表

            final String sql1 = "update %s set settlementNum=settlementNum-%s, settledNum=settledNum+%s ," +
                    "amountSettledMoney=(amountSettledMoney + (unitPrice * %s ))  where objectId='%s'";

            settleData.forEach((k,v)->{
                String updateApplyProcessIn = String.format(sql1, "i_applyprocessin", v, v, v, k);
                logger.info("更入库表sql : {}", updateApplyProcessIn);
                getEngine().getPortalQuery().ExcuteNoQuery(updateApplyProcessIn);
            });


            final String sql2 = "update %s set settlementNum=settlementNum-%s, settledNum=settledNum+%s where objectId='%s'";

            logger.info("更新主流程数据值 : {}", inSettleData);
            //数据回写到 主流程子表
            inSettleData.forEach((k,v)->{
                String updateApplyOutsource = String.format(sql2, "i_applyOutsource", v, v, k);
                logger.info("更新主流程sql : {}", updateApplyOutsource);
                getEngine().getPortalQuery().ExcuteNoQuery(updateApplyOutsource);
            });

            final String sql3 ="update %s set settleMoney= %s where objectId='%s'";
            logger.info("本次结算总金额 = {}",settleMoney);
            String monthlySettlement = String.format(sql3, "i_monthlySettlement", settleMoney, objectId);
            logger.info("本次结算总金额sql = {}",monthlySettlement);
            getEngine().getPortalQuery().ExcuteNoQuery(monthlySettlement);
            processDataSave(objectId,"validProcessOutFlag",pass);

            return pass;

        } catch (Exception e) {
            e.printStackTrace();
            notPass = "系统异常";
            return  notPass;
        }


    }

    @Override
    public boolean processInDetails(String objectId, String outsourceTitle,String partnerUnit, String applicationUnitId) {
       try {
           String sqlCount2= "SELECT count(b.ObjectID) FROM i_processIn a left join i_applyProcessIn b on a.ObjectID = b.ParentObjectID and b.ParentObjectID = '%s' and a.partnerUnit= '%s' and a.outsourceTitle ='%s' and outsourcingNo is not null and outsourcingNo!=''";
           String sqlCountFormat = String.format(sqlCount2, objectId, partnerUnit,outsourceTitle);
           int count = getEngine().getPortalQuery().count(sqlCountFormat);
           logger.info("查询已暂存,入库数sql={}",sqlCountFormat);
           logger.info("查询已暂存的数据为:{}",count);
           if(count>=1){

           }else {
               String deleteSql ="delete from i_applyProcessIn where ParentObjectID ='"+objectId+"'";
               getEngine().getPortalQuery().ExcuteNoQuery(deleteSql);
               logger.info("入库保存时,删除数据sql : {}",deleteSql);
               String sql="SELECT a1.outsourceTitle,a1.partnerUnit,a1.validProcessOutFlag,a1.organizer,a2.vehicleNum,a2.vehicleModel,a2.outsourceNum,a2.jobContent,a2.productName,a2.workNum,a2.processOutNum,a2.outsourcingNo,a2.approvedNum,a2.serialNum,a2.productNum,a2.workOrderNum,a2.productionProcesses,a2.unit,a2.workOrderName,a2.processedOutNum,a2.figureModel,a2.processOutNo,a2.applicationFormId,a2.unitPrice,a2.processedInNum,a2.ObjectID as processOutObjId,a2.contractNo,a2.taskNum,a2.approvedNum from i_processout a1 LEFT JOIN i_applyprocessout a2 ON a1.ObjectID = a2.ParentObjectID WHERE a1.outsourceTitle = '%s' and a1.partnerUnit = '%s' and a2.processOutNum>a2.processedInNum and a1.applicationUnitId = '%s' and a1.validProcessOutFlag = '通过'";
               String detailsSql = String.format(sql, outsourceTitle, partnerUnit, applicationUnitId);
               logger.info("查询待入库sql = {}",detailsSql);
               DataTable dataTable = getEngine().getPortalQuery().QueryTable(detailsSql);
               int returnNum;
               for (int i = 0; i < dataTable.getRows().size(); i++) {
                   outsourceTitle =  dataTable.getRows().get(i).getString("outsourceTitle");
                   partnerUnit =  dataTable.getRows().get(i).getString("partnerUnit");
                   String validProcessOutFlag =  dataTable.getRows().get(i).getString("validProcessOutFlag");
                   String organizer =  dataTable.getRows().get(i).getString("organizer");
                   String vehicleNum =  dataTable.getRows().get(i).getString("vehicleNum");
                   String vehicleModel =  dataTable.getRows().get(i).getString("vehicleModel");
                   String outsourceNum =  dataTable.getRows().get(i).getString("outsourceNum");
                   String jobContent =  dataTable.getRows().get(i).getString("jobContent");
                   String productName =  dataTable.getRows().get(i).getString("productName");
                   String workNum =  dataTable.getRows().get(i).getString("workNum");
                   int processOutNum =  dataTable.getRows().get(i).getInt("processOutNum");
                   String outsourcingNo =  dataTable.getRows().get(i).getString("outsourcingNo");
                   String approvedNum =  dataTable.getRows().get(i).getString("approvedNum");
                   String serialNum =  dataTable.getRows().get(i).getString("serialNum");
                   String productNum =  dataTable.getRows().get(i).getString("productNum");
                   String workOrderNum =  dataTable.getRows().get(i).getString("workOrderNum");
                   String productionProcesses =  dataTable.getRows().get(i).getString("productionProcesses");
                   String unit =  dataTable.getRows().get(i).getString("unit");
                   String workOrderName =  dataTable.getRows().get(i).getString("workOrderName");
                   String processedOutNum =  dataTable.getRows().get(i).getString("processedOutNum");
                   String figureModel =  dataTable.getRows().get(i).getString("figureModel");
                   String processOutNo =  dataTable.getRows().get(i).getString("processOutNo");
                   String applicationFormId =  dataTable.getRows().get(i).getString("applicationFormId");
                   String unitPrice =  dataTable.getRows().get(i).getString("unitPrice");
                   int processedInNum =  dataTable.getRows().get(i).getInt("processedInNum");
                   String processOutObjId =  dataTable.getRows().get(i).getString("processOutObjId");
                   String contractNo =  dataTable.getRows().get(i).getString("contractNo");
                   String taskNum =  dataTable.getRows().get(i).getString("taskNum");
                   returnNum =processOutNum - processedInNum;
                   BigDecimal price=new BigDecimal(unitPrice);
                   BigDecimal num=new BigDecimal(returnNum);
                   BigDecimal multiply = price.multiply(num);
                   String insertSql ="insert into i_applyProcessIn (outsourcingNo,productNum,productName,figureModel,productionProcesses,jobContent,unit,outsourceNum,approvedNum,returnNum,returningNum,qualifyingNum,partnerUnit,serialNum,applicationFormId,processOutObjId,workOrderNum,workNum,workOrderName,vehicleModel,vehicleNum,contractNo,unitPrice,taskNum,ParentObjectID,ObjectID,ParentPropertyName,ParentIndex,SettledNum,failingNum,settlementNum) value ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');";
                   String insertDetailsSql = String.format(insertSql, outsourcingNo,productNum,productName,figureModel,productionProcesses,jobContent,unit,outsourceNum,approvedNum,returnNum,returnNum,returnNum,partnerUnit,serialNum,applicationFormId,processOutObjId,workOrderNum,workNum,workOrderName,vehicleModel,vehicleNum,contractNo,unitPrice,taskNum,objectId,UUID.randomUUID().toString(),"applyProcessIn","0",0,0,returnNum);
                   logger.info("入库sql = {}",insertDetailsSql);
                   getEngine().getPortalQuery().ExcuteNoQuery(insertDetailsSql);
               }
           }
           return true;
       }catch (Exception e){
           e.printStackTrace();
           return false;
       }
    }

    @Override
    public boolean monthlySettlementDetails(String objectId,String partnerUnit, String applicationUnitId) {
        try {
            String sqlCount="SELECT count(b.ObjectID) FROM i_monthlySettlement a left join i_settlementSub b ON a.ObjectID=b.ParentObjectID  and b.ParentObjectID = '%s' and a.partnerUnit= '%s'  and productName is not null and productName!=''";
            String sqlCountFormat = String.format(sqlCount, objectId, partnerUnit);
            int count = getEngine().getPortalQuery().count(sqlCountFormat);
            logger.info("查询已暂存,结算数sql={}",sqlCountFormat);
            logger.info("查询已暂存的数据为:{}",count);
            if(count>=1){


            }else{
                String deleteSql ="delete from i_settlementSub where ParentObjectID ='"+objectId+"'";
                logger.info("月度结算保存时,删除数据sql : {}",deleteSql);
                getEngine().getPortalQuery().ExcuteNoQuery(deleteSql);
                String sql="SELECT a2.productName,a2.figureModel,a2.settlementNum,a2.unit,a2.contractNo,a2.workOrderNum,a2.workNum,a2.unitPrice,a1.organizer,a2.vehicleNum,a2.vehicleModel,a1.sequenceNum,a1.applicationUnit,a2.ObjectID as applyProcessInId,a1.outsourceTitle,a2.outsourceNum,a2.taskNum  from i_processin a1 right join i_applyprocessin a2 on a1.ObjectID = a2.ParentObjectID WHERE a2.qualifyingNum > a2.SettledNum and a1.applicationUnitId = '%s' and a1.partnerUnit = '%s' and a1.validFlag= '通过'";
                String detailsSql = String.format(sql, applicationUnitId, partnerUnit);
                logger.info("查询待结算sql = {}",detailsSql);
                DataTable dataTable = getEngine().getPortalQuery().QueryTable(detailsSql);
                for (int i = 0; i < dataTable.getRows().size(); i++) {
                    String productName =  dataTable.getRows().get(i).getString("productName");
                    String figureModel =  dataTable.getRows().get(i).getString("figureModel");
                    String settlementNum =  dataTable.getRows().get(i).getString("settlementNum");
                    String unit =  dataTable.getRows().get(i).getString("unit");
                    String contractNo =  dataTable.getRows().get(i).getString("contractNo");
                    String workOrderNum =  dataTable.getRows().get(i).getString("workOrderNum");
                    String workNum =  dataTable.getRows().get(i).getString("workNum");
                    String unitPrice =  dataTable.getRows().get(i).getString("unitPrice");
                    String organizer =  dataTable.getRows().get(i).getString("organizer");
                    String vehicleNum =  dataTable.getRows().get(i).getString("vehicleNum");
                    String vehicleModel =  dataTable.getRows().get(i).getString("vehicleModel");
                    String sequenceNum =  dataTable.getRows().get(i).getString("sequenceNum");
                    String applicationUnit =  dataTable.getRows().get(i).getString("applicationUnit");
                    String applyProcessInId =  dataTable.getRows().get(i).getString("applyProcessInId");
                    String outsourceTitle =  dataTable.getRows().get(i).getString("outsourceTitle");
                    String outsourceNum =  dataTable.getRows().get(i).getString("outsourceNum");
                    String taskNum =  dataTable.getRows().get(i).getString("taskNum");
                    BigDecimal price=new BigDecimal(unitPrice);
                    BigDecimal num=new BigDecimal(settlementNum);
                    BigDecimal multiply = price.multiply(num);
                    String insertSql ="insert into i_settlementSub (applicationUnit,sequenceNum,vehicleModel,vehicleNum,productName,figureModel,workNum,workOrderNum,unit,contractNo,unitPrice,settlementNum,organizer,applyProcessInId,settleNum,outsourceNum,taskNum,amount,ParentObjectID,ObjectID,ParentPropertyName,ParentIndex) value ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
                    String insertDetailsSql = String.format(insertSql, applicationUnit,sequenceNum,vehicleModel,vehicleNum,productName,figureModel,workNum,workOrderNum,unit,contractNo,unitPrice,settlementNum,organizer,applyProcessInId,settlementNum,outsourceNum,taskNum,multiply,objectId, UUID.randomUUID().toString(),"settlementSub","0");
                    logger.info("结算sql = {}",insertDetailsSql);
                    getEngine().getPortalQuery().ExcuteNoQuery(insertDetailsSql);
                }
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    @Override
    public boolean processInCleanUp(String objectId) {
        try {
            String sqlDelete= "delete  FROM i_applyProcessIn WHERE ParentObjectID = '"+objectId+"' AND (outsourcingNo is null OR outsourcingNo=='')";
            int count = getEngine().getPortalQuery().ExcuteNoQuery(sqlDelete);
            logger.info("删除入库空白数据,sql={}",sqlDelete);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean monthlySettlementCleanUp(String objectId) {
        try {
            String sqlDelete= "delete  FROM i_settlementSub WHERE ParentObjectID = '"+objectId+"'  and (productName is null and productName='')";
            getEngine().getPortalQuery().ExcuteNoQuery(sqlDelete);
            logger.info("删除月度结算空白数据,sql={}",sqlDelete);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    private  Map<String,Integer>  getSettleData(DataTable dataTable ){
        List<DataRow> entityRows = dataTable.getEntityRows();

        Map<String, Integer> settleMap = new HashMap<>();

        entityRows.stream().forEach(a->{

            try {

                settleMap.put(a.getString("applyProcessInId"),QjcUtils.getInt(settleMap.get(a.getString("applyProcessInId")))+a.getInt("settleNum"));

            } catch (DataException e) {
                e.printStackTrace();
            }
        });
        return  settleMap;
    }

    public Map<String,Integer> getProcessData(DataRowCollection rows) throws Exception {

        if (rows.size() == 0){
            return  null;
        }

        Map<String,Integer> processData = new HashMap<>(rows.size());
        String applicationFormId;

        Integer processOutNum;

        for (int i=0 ;i<rows.size();i++ ) {

            //获取外包项目编码,产品编码,批准数量,已出门数,出门数
            applicationFormId = rows.get(i).getString("applicationFormId");

            processOutNum = rows.get(i).getInt("processOutNum");

            processData.put(applicationFormId,processOutNum + QjcUtils.getInt( processData.get(applicationFormId) ));

        }


        return  processData;

    }

    /**
     * 查询出门数据的已入库数
     * @param rows
     * @return
     * @throws Exception
     */
    public Map<String,Integer> getProcessInData(DataRowCollection rows) throws Exception {

        if (rows.size() == 0){
            return  null;
        }

        Map<String,Integer> processData = new HashMap<>(rows.size());
        String processOutObjId;

        Integer returningNum;
        //processOutNum>processedInNum
        for (int i=0 ;i<rows.size();i++ ) {

            //获取
            processOutObjId = rows.get(i).getString("processOutObjId");

            returningNum = rows.get(i).getInt("returningNum");

            processData.put(processOutObjId,returningNum);

        }


        return  processData;

    }

}
